﻿using Microsoft.Extensions.DependencyInjection;
using MingYuanYun.Context.Abstractions;
using MingYuanYun.Data.Abstractions;
using MingYuanYun.StructuredLog.Abstractions;
using System;
using System.Collections.Generic;
using System.Text;

namespace ControlCenter.Operation
{
    public class OperationBase
    {
        private readonly IUnitOfWork _unitOfWork;

        private IMyLogger _logger;

        public OperationBase(IServiceContext context, IUnitOfWork unitOfWork)
        {
            this._unitOfWork = unitOfWork;

            this.ServiceContext = context;
        }

        protected IServiceContext ServiceContext { get; }

        protected IMyLogger Logger => this._logger ?? (this._logger = this.GetService<IMyLogger>());

        protected T GetRepository<T>() where T : IRepositoryBase
        {
            var repository = this.GetService<T>();

            repository.UnitOfWork = this._unitOfWork;

            return repository;
        }

        /// <summary>
        /// Get the config section in json file and deserialize to class.
        /// </summary>
        protected T GetConfig<T>(string sectionName)
        {
            return this.ServiceContext.GetConfig<T>(sectionName);
        }

        /// <summary>
        /// Get the injected service, if the service doesn't inject at startup, it will throw exception.
        /// </summary>
        protected T GetService<T>()
        {
            return this.ServiceContext.GetService<T>();
        }

        /// <summary>
        /// Create the specific scope for committing transaction.
        /// </summary>
        /// <returns></returns>
        protected IServiceScope CreateScope()
        {
            return this.ServiceContext.CreateScope();
        }
    }
}
